package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 一般表单都是POST提交数据,解决POST乱码
        // request.setCharacterEncoding("UTF-8");

        // 1.接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        // 2.调用service查询User
        UserService userService = new UserService();
        User user = userService.login(username, password);

        // 3.判断User是否为null
        if (user != null) {
            // 登录成功
            // 判断是否勾选记住我
            if ("1".equals(remember)) {
                // 把账号密码放到Cookie写给浏览器
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("password", password);
                cookie1.setMaxAge(60 * 60 * 24 * 7);
                cookie2.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }

            // 将用户名保存到Session
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            // 重定向到主页
            response.sendRedirect("selectAllServlet");
        } else {
            // 登录失败
            // 往请求域中保存数据
            request.setAttribute("loginMessage", "用户名或密码错误");
            // 转发到登录页面
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
